package org.jeecg.modules.flow.callback.move;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.business.repertory.service.IWmsRepertoryService;
import org.jeecg.modules.business.strategy.entity.MesSite;
import org.jeecg.modules.business.strategy.service.IMesSiteService;
import org.jeecg.modules.business.third.service.IEmsOrDmsDeliveryOperateService;
import org.jeecg.modules.business.third.strategy.emsdms.consts.EmsSystemConst;
import org.jeecg.modules.business.transfer.entity.WmsMoveReceipt;
import org.jeecg.modules.business.transfer.entity.WmsMoveReceiptMaterial;
import org.jeecg.modules.business.transfer.service.IWmsMoveReceiptService;
import org.jeecg.modules.dock.config.JsonUtils;
import org.jeecg.modules.dock.entity.dto.request.ZJCallBucketRequest;
import org.jeecg.modules.dock.entity.ems.response.EmsBaseResponseVO;
import org.jeecg.modules.dock.entity.mes.request.MesBaseRequestVO;
import org.jeecg.modules.dock.entity.mes.request.VerticalCuttingIsCalledPaperTubeRequestVO;
import org.jeecg.modules.dock.service.EmsDockingRepeaterService;
import org.jeecg.modules.dock.service.MesDockingRepeaterService;
import org.jeecg.modules.flow.sys.common.BaseCustomBeanRun;
import org.jeecg.modules.flow.sys.entity.dto.BaseFlowDto;
import org.jeecg.modules.flow.sys.service.WorkFlowService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 纵剪叫纸筒 通知叫纸筒 回调Bean
 *
 * @author lumingyi
 * @version 1.0.0
 * @since 2023-11-16
 */
@RequiredArgsConstructor
@Component
@Slf4j
public class Y14MoveNoticeBean<T> extends BaseCustomBeanRun<T> {

    private final IEmsOrDmsDeliveryOperateService emsOrDmsDeliveryOperateService;

    private final IWmsMoveReceiptService moveReceiptService;
    private final EmsDockingRepeaterService emsDockingRepeaterService;
    private final org.jeecg.modules.business.transfer.service.IWmsMoveReceiptMaterialService iWmsMoveReceiptMaterialService;
    private final IMesSiteService iMesSiteService;
    private final WorkFlowService workFlowService;
    private final MesDockingRepeaterService mesDockingRepeaterService;
    private final IWmsRepertoryService wmsRepertoryService;
    /**
     * 业务逻辑 纵剪叫纸筒 通知叫纸筒
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void actureRun() {
        BaseFlowDto baseFlowDto = this.getBaseFlowDto();
        String id = baseFlowDto.getInfoId();
        boolean result = false;
        String msg = "";
        // 主动调用EMS发送叫纸筒请求
        WmsMoveReceipt moveReceipt = moveReceiptService.getById(baseFlowDto.getInfoId());
        ZJCallBucketRequest bean = null;
        if (ObjectUtil.isNotNull(moveReceipt)) {
            WmsMoveReceiptMaterial wmsMoveReceiptMaterial = iWmsMoveReceiptMaterialService.getOne(new LambdaQueryWrapper<WmsMoveReceiptMaterial>()
                    .eq(WmsMoveReceiptMaterial::getWmsMoveReceiptId, moveReceipt.getId()).last("limit 1"));
            if (ObjectUtil.isNotNull(wmsMoveReceiptMaterial)) {
                if (StringUtils.isNotBlank(wmsMoveReceiptMaterial.getExtraText())) {
                    VerticalCuttingIsCalledPaperTubeRequestVO vo = JSON.parseObject(wmsMoveReceiptMaterial.getExtraText(), VerticalCuttingIsCalledPaperTubeRequestVO.class);
                    bean = JsonUtils.toBean(wmsMoveReceiptMaterial.getExtraText(), ZJCallBucketRequest.class);
                    bean.setOperateTime(new Date());
                    // 根据站点查询MES站点
                    MesSite one = iMesSiteService.getOne(new LambdaQueryWrapper<MesSite>()
                            .eq(MesSite::getAskMaterialSite, vo.getSite()));
                    if (ObjectUtil.isNotNull(one)) {
                        bean.setSite(one.getPaperTubeStationDown());
                        bean.setPrepareSite(EmsSystemConst.PAPER_TUBE_STATION_UP);
                    }
                    bean.setDetails(vo.getDetail());
                    try {
                        EmsBaseResponseVO emsBaseResponseVO = emsDockingRepeaterService.zjCallBucket(bean);
                        if ("success".equals(emsBaseResponseVO.getTarget())) {
                            result = true;
                        }
                        msg = emsBaseResponseVO.getMsg();
                    } catch (Exception e) {
                        log.error("纵剪叫纸筒通知ems失败", e);
                    }
                }
            }
        }
        if (!result) {
            baseFlowDto.setCurrentFailed(true);
            if (StringUtils.isNotBlank(msg)) {
                baseFlowDto.setResult(Result.error(msg));
            } else {
                baseFlowDto.setResult(Result.error("通知EMS可配送执行失败"));
            }
            // 强制关闭任务
            workFlowService.interrupt(baseFlowDto);
            // 把强制关闭任务，状态，原因同步给mes
            MesBaseRequestVO mesBaseRequestVO = new MesBaseRequestVO();
            BeanUtils.copyProperties(bean, mesBaseRequestVO);
            mesBaseRequestVO.setOperateTime(new Date());
            mesBaseRequestVO.setOperateReason("强制关闭叫纸筒任务");
            try {
                mesDockingRepeaterService.updateStatus(mesBaseRequestVO);
            } catch (Exception e) {
                log.error("强制关闭叫纸筒任务报错, []", e);
            }
        } else {
            // 当前前端调用业务需要你返回的
            baseFlowDto.setResult(Result.OK());
            // id是保存业务记录的id。用于生成业务流程信息记录
            baseFlowDto.setInfoId(id);
        }
    }
}
